package service

import (
	"encoding/json"
	"gin/model"
	uuid "github.com/satori/go.uuid"
	"github.com/spf13/viper"
	teamones_helper "github.com/teamones-open/go-helper"
	"github.com/valyala/fasthttp"
	"strings"
	"time"
)

type AuthValidateRemote struct {
	Code int64  `json:"code"`
	Msg  string `json:"msg"`
	Data struct {
		UserId  uint64 `json:"user_id"`
		Expires uint64 `json:"expires"`
	} `json:"data"`
}

// 生成密钥对
func GenerateToken() (accessKey string, secretKey string, err error) {
	// 生成token
	authUUID := uuid.NewV4().String()
	var authModel model.Auth
	authModel.AccessKey = teamones_helper.GenerateMd5(authUUID + "_access_key")
	authModel.SecretKey = teamones_helper.GenerateMd5(authUUID + "_secret_key")

	accessKey, secretKey, err = authModel.Generate()

	return
}

// 获取密钥对
func GetToken() (accessKey string, secretKey string, err error) {
	var authModel model.Auth
	accessKey, secretKey, err = authModel.GetToken()
	return
}

// 验证token是否正确
func CheckToken(token string) (check bool) {
	accessKey, secretKey, err := GetToken()
	if err != nil {
		return false
	} else {
		md5 := teamones_helper.GenerateMd5(accessKey + secretKey)
		if token != md5 {
			return false
		}
	}
	return true
}

// CheckTokenRemote 远程检查token
func CheckTokenRemote(token, deviceCode, ip string) (flag bool, authResp AuthValidateRemote) {
	imDomain := viper.GetString("oauth.url")

	// 初始化http对象
	req := &fasthttp.Request{}

	// 设置路由
	req.SetRequestURI(imDomain + "/oauth/check_token")

	// 设置Header
	req.Header.SetUserAgent("pan.baidu.com")
	req.Header.Set("Device-Unique-Code", deviceCode)

	// 设置请求方式
	req.Header.SetMethod("POST")

	paramMap := map[string]string{
		"ip":                 ip,
		"access_token":       token,
		"device_unique_code": deviceCode,
	}
	paramStr := ""
	for k, v := range paramMap {
		paramStr += k + "=" + v + "&"
	}
	paramStr = strings.TrimRight(paramStr, "&")

	// 增加参数
	req.SetBodyString(paramStr)

	// 获取请求数据
	client := &fasthttp.Client{}
	resp := &fasthttp.Response{}
	err := client.DoTimeout(req, resp, time.Second*2)

	if err != nil {
		return
	}
	_ = json.Unmarshal(resp.Body(), &authResp)

	if authResp.Code == 0 {
		flag = true
	}

	return

}
